package com.hdy.web.controller;

import com.hdy.web.service.ReadExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.hdy.web.pojo.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/excelFile")
@Slf4j
public class ExcelFileController {
    @Autowired
    ReadExcel readExcel;
    @Value("${upload.directory}") // 通过配置文件设置上传文件的保存目录
    private String uploadDirectory;
    @ResponseBody
    @RequestMapping("/upload")
    public ResponseEntity<String>  upload(@RequestParam("file") MultipartFile file,@RequestParam("is_participate") boolean isParticipate,@RequestParam(value = "InsuranceFee",required = false) Integer insurance,HttpServletRequest request) {
        boolean is_success;
        is_success = readExcel.calculate(file,isParticipate,insurance,request);
        if (!is_success)
            return ResponseEntity.of(99,"fail",null);
        return ResponseEntity.success("success",null);
    }
    @PostMapping("/download")
    public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String userName =(String) request.getSession().getAttribute("userName");
        String fileName = userName+".xlsx"; // Excel 文件名
        String filePath = System.getProperty("user.dir") + File.separator + fileName; // 构建文件路径
        log.info(filePath);
        File file = new File(filePath);

        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 读取文件并写入响应的输出流
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        // 关闭输入流和输出流
        response.flushBuffer();
        file.delete();
    }
}
